package com.merry.mvc.controller;

import com.merry.mvc.bean.Age;
import com.merry.mvc.bean.User;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.*;

@Controller
@RequestMapping("/user")
public class UserController {
    //RESTFul demo

    @GetMapping("/user/{id}")
    public ModelAndView getUser(@PathVariable("id") String id,ModelAndView mv){
        mv.setViewName("user");
        mv.addObject("userId","get user id:"+id);
        return mv;
    }

    @PostMapping(value = "/user")
    public ModelAndView postUser(@RequestBody User user,ModelAndView mv){
        mv.setViewName("user");
        mv.addObject("userId","post user id:"+user.getId());
        return mv;
    }

    @PutMapping("/user/{id}")
    public ModelAndView putUser(@PathVariable("id") String id,ModelAndView mv){
        mv.setViewName("user");
        mv.addObject("userId","put user id:"+id);
        return mv;
    }

    @DeleteMapping("/user/{id}")
    public ModelAndView deleteUser(@PathVariable("id") String id,ModelAndView mv){
        mv.setViewName("user");
        mv.addObject("userId","delete user id:"+id);
        return mv;
    }

    @GetMapping("/getResponseBody")
    @ResponseBody
    public Age getAge(){
        Age age = new Age();
        age.setAge("12");
        return age;
    }

    //实现下载功能
    @RequestMapping("/fileDownload")
    public ResponseEntity<byte[]> download(HttpServletRequest request) throws Exception {
        //获取session对象
        HttpSession session = request.getSession();
        //获取servletContext对象
        ServletContext servletContext = session.getServletContext();
        //获取服务器中文件的真实路径
        String realPath = servletContext.getRealPath("/static/node1.txt");
        //创建输入流
        FileInputStream fileInputStream = new FileInputStream(realPath);
        //创建字节数组
        byte[] bytes =new byte[fileInputStream.available()];
        //将流读到字节数组中
        fileInputStream.read(bytes);
        //创建header对象设置头信息
        MultiValueMap<String,String> headers=new HttpHeaders();
        //设置下载方式以及下载文件的名字
        headers.add("Content-Disposition","attachment;filename=node1.txt");
        //设置响应状态码
        HttpStatus ok = HttpStatus.OK;
        //创建ResponseEntity对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(bytes,headers,ok);
        //关闭输入流
        fileInputStream.close();
        return responseEntity;
    }


    //实现上传功能
    @RequestMapping("/upload")
    public String upload(MultipartFile photo,HttpSession session) throws IOException {
        String filename = photo.getOriginalFilename();
        ServletContext servletContext = session.getServletContext();
        //这个路径可能不存在，为一个虚假的地址
        String photoPath = servletContext.getRealPath("photo");
        File file = new File(photoPath);
        //判断路径对应的文件是否存在
        if(!file.exists()){
            //若不存在，创建目录
            file.mkdir();
        }
        String finalPath = photoPath + File.separator + filename;
        photo.transferTo(new File(finalPath));
        return "user";
    }

    //测试异常处理器
    @RequestMapping("/error")
    public String error(){
        throw new ArithmeticException();
    }
}
